<?php

namespace App\Http\Controllers;

use App\Models\Eticket\Activity;
use App\Models\Eticket\Join;
use App\Models\Eticket\Ticket;
use App\User;
use Auth;
use EasyWeChat\Message\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class EticketController extends Controller
{
    protected $student;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    //先构造函数，再中间件，再callAction
    public function callAction($method, $parameters)
    {
        $this->student = session('student');
        return parent::callAction($method, $parameters); // TODO: Change the autogenerated stub
    }

    /**
     * 我的门票
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        echo '我的门票';
    }

    public function ajaxIndex()
    {
        return response()->json($this->student->tickets()->where('status', Ticket::OCCUPIED)->first());
    }

    /**
     * 更多门票及历史记录
     */
    public function history()
    {
        echo '更多门票及历史记录';
    }

    public function ajaxHistory()
    {
        return response()->json($this->student->tickets);
    }

    /**
     * 学校活动
     */
    public function activities()
    {
        echo '学校活动';
    }

    public function ajaxActivities()
    {
        $data['activities'] = $this->student->activities;
        foreach ($data['activities'] as $activity) {
            $activity->types = Ticket::select('type')->distinct()->where('activity_id', $activity->id)->get();
            $activity->online;
            $join = Join::where('activity_id', $activity->id)->where('openid', $this->student->openid)->first();
            if ($join) {
                $activity->join = $join->number;
            } else {
                $activity->join = null;
            }
        }
        return response()->json($data);
    }

    /**
     * 活动详情(貌似没用)
     * @param $id
     */
    public function activity($id)
    {

    }

    public function ajaxActivity($id)
    {

    }

    /**
     * 线上参与活动
     */
    public function join($id)
    {
        $join = Join::where('activity_id', $id)->where('openid', $this->student->openid)->first();
        if ($join) {
            return response()->json(['status' => 1, 'number' => $join->number]);
        }
        $number = Join::where('activity_id', $id)->count();
        $join = new Join();
        $join->activity_id = $id;
        $join->openid = $this->student->openid;
        $join->number = $number + 1;
        $join->status = Join::INIT;
        $join->save();
        return response()->json(['status' => 0, 'number' => $join->number]);
    }

    /**
     * 转送
     * 门票页面分享出去的链接打开为此函数
     */
    public function transfer($tid)
    {
        $ticket = Ticket::find($tid);
        if (!$ticket || $ticket->status != Ticket::OCCUPIED) {
            return response()->json(['status' => 1, 'error' => '此门票不存在或不可转送']);
        }
        if ($ticket->openid == $this->student->openid) {
            return response()->json(['status' => 2, 'error' => '不可转送给自己']);
        }
        $newTicket = clone $ticket;
        $ticket->status = Ticket::TURN_OUT;
        $ticket->save();
        $newTicket->openid = $this->student->openid;
        $newTicket->save();
        return response()->json(['status' => 0, 'error' => '转送成功']);

    }

    /**
     * 二维码URL
     */
    public function qrcodeUrl($tid)
    {
        $ticket = Ticket::find($tid);
        if (!$ticket || $ticket->status != Ticket::OCCUPIED || $ticket->openid != $this->student->openid) {
            return response()->json(['status' => 1, 'error' => '未拥有此门票']);
        }
        $key = env('APP_KEY');
        $timestamp = strtotime(date('Y-m-d H:i'));
        $token = base64_encode($tid . '@' . md5($this->student->openid . $key . $timestamp));
        return response()->json(['status' => 0, 'url' => url('eticket/writeOff/' . $token)]);
    }

    /**
     * 核销
     * 二维码生成机制：
     *  每分钟刷新一次
     */
    public function writeOff($token)
    {
        list($tid, $md5) = explode('@', base64_decode($token));
        $key = env('APP_KEY');
        $timestamp = strtotime(date('Y-m-d H:i'));
        $ticket = Ticket::find($tid);
        if (!$ticket) {
            return response()->json(['status' => 1, 'error' => '此门票不存在'], 404);
        }
        if ($md5 == md5($ticket->openid . $key . $timestamp) && $ticket->status == Ticket::OCCUPIED) {
            $ticket->status = Ticket::DESTROY;
            $ticket->save();
            return response()->json(['status' => 0, 'error' => '核销成功']);
        }
        return response()->json(['status' => 1, 'error' => '二维码不正确']);
    }

    /**
     * 我的奖品
     */
    public function myPrizes()
    {

    }

    /**
     * 线下扫码,扫描参数二维码回调函数
     * @param int $aid 活动ID
     * @param int $way 线上or线下
     * @param string $type 票种
     * @param $openid
     * @return string
     */
    public static function offlineScan($aid, $way, $type, $openid='')
    {
        $activity = Activity::find($aid);
        if (empty($activity) || $way != Ticket::OFFLINE) {
            return '二维码失效';
        }
        //回复图文消息
        $news = new News([
            'title'       => "点击领取「{$activity->name}」{$type}门票",
            'description' => '',
            'url'         => url("eticket/offlineGetTicket/{$aid}/{$way}/{$type}"),
            'image'       => 'https://img6.bdstatic.com/img/image/pcindex/xiaoqingxinxinxin.jpg',
            // ...
        ]);
        return $news;
    }

    public function offlineGetTicket($aid, $way, $type)
    {
        $activity = Activity::find($aid);
        if (empty($activity) || $way != Ticket::OFFLINE) {
            return response('领取失败');
        }

        $ticket = Ticket::where('activity_id', $aid)
            ->where('way', $way)
            ->where('type', $type)
            ->where('status', 0)
            ->first();
        if (!$ticket) {
            return response('领取失败');
        }
        $ticket->openid = $this->student->openid;
        $ticket->status = Ticket::OCCUPIED;
        if ($ticket->save()) {
            return response('领取成功');
        }
        return response('领取失败');
    }
}
